package hub.cathome.controller;

import hub.cathome.entity.tool.ApplicationProperties;
import hub.cathome.service.ResourceService;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.activation.MimetypesFileTypeMap;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Controller
public class ResourceController {
    @Resource(name="resourceService")
    private ResourceService resourceService;
    @RequestMapping("/img_res/**/{path}")
    public ResponseEntity<byte[]> download(@PathVariable String path, @RequestHeader("User-Agent") String userAgent,HttpServletRequest request, HttpServletResponse response) throws IOException {
        path = request.getServletPath().substring("/img_res/".length());
        File file = new File(ApplicationProperties.getAbsoluteLocalPath(path));
        if(!file.exists()){
            file = new File(ApplicationProperties.getDefaultImgPath());
        }
        System.out.println(file);
        HttpHeaders headers = new HttpHeaders();
        response.setContentType(new MimetypesFileTypeMap().getContentType(file)); // 设置response内容的类型
        if(userAgent.indexOf("MISE")>0||userAgent.indexOf("Trident")>0||userAgent.indexOf("Edge")>0){
            try{
                headers.setContentDispositionFormData("attachment", URLEncoder.encode(path,"UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }else{
            headers.setContentDispositionFormData("attachment",new String(file.getAbsolutePath().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        }
        return new ResponseEntity<>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
    }
}
